﻿using System;
using System.Windows;
using System.Windows.Controls;

namespace PocketBook.Controls
{
    // Truncates panel width and height to be a multiple of UnitSize.
    //
    public class IntegralPanel : Panel
    {
        public static readonly DependencyProperty UnitSizeProperty =
            DependencyProperty.Register("UnitSize", typeof(double), typeof(IntegralPanel),
                new FrameworkPropertyMetadata(32d, FrameworkPropertyMetadataOptions.AffectsMeasure));

        public double UnitSize
        {
            get { return (double)GetValue(UnitSizeProperty); }
            set { SetValue(UnitSizeProperty, value); }
        }

        protected override Size MeasureOverride(Size availableSize)
        {
            availableSize = TruncateSize(availableSize);

            foreach (UIElement element in InternalChildren)
            {
                element.Measure(availableSize);
            }

            return base.MeasureOverride(availableSize);
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            var bounds = new Rect(TruncateSize(finalSize));

            foreach (UIElement element in InternalChildren)
            {
                element.Arrange(bounds);
            }

            return base.ArrangeOverride(bounds.Size);
        }

        private Size TruncateSize(Size size)
        {
            return new Size(TruncateLength(size.Width), TruncateLength(size.Height));
        }

        private double TruncateLength(double length)
        {
            return !Double.IsNaN(length) && !Double.IsPositiveInfinity(length) && UnitSize > 0
                ? Math.Truncate(length / UnitSize) * UnitSize
                : length;
        }
    }
}